import { CozeAPI, COZE_COM_BASE_URL, ChatStatus, RoleType, ChatEventType } from '@coze/api';
import { configSetParam } from "@/utils";
import IRequest from "@/config/request";
import http from 'axios'

// Initialize client with your Personal Access Token
const client = new CozeAPI({
  token: configSetParam.token, // Get your PAT from https://www.coze.com/open/oauth/pats
  baseURL: 'https://api.coze.cn',
  allowPersonalAccessTokenInBrowser: true
});
export async function streamChat(message: string) {
  let result = ''
  const stream = await client.chat.stream({
    bot_id: configSetParam.botId,
    additional_messages: [{
      role: RoleType.User,
      content: message,
      content_type: 'text',
      type: 'question',
    }],
  });
  console.log('stream--------', stream)
  // for await (const part of stream) {
  //   if (part.event === ChatEventType.CONVERSATION_MESSAGE_COMPLETED) {
  //     const { role, type, content } = part.data;
  //     if (role === 'assistant' && type === 'answer') {
  //       result = content
  //       console.log('content-----', content)
  //     } else {
  //       console.log('[%s]:[%s]:%s', role, type, content);
  //     }
  //   }
  // }
  handleStreamResponse(stream)
  // return stream
  // return result
}
const handleStreamResponse = async (response) => {
  const reader = response.getReader();
  const decoder = new TextDecoder('utf-8');
  let accumulatedText = '';
  // 更新连接状态
  // document.getElementById('connection-status').textContent = '连接状态: 接收中';
  while (true) {
    const { done, value } = await reader.read();
    if (done) {
      // document.getElementById('connection-status').textContent = '连接状态: 就绪';
      break;
    }
    
    // 解码数据
    const chunk = decoder.decode(value, { stream: true });
    // 处理SSE格式的数据
    const lines = chunk.split('\n').filter(line => line.trim() !== '');
    for (const line of lines) {
      if (line.startsWith('data: ')) {
        const data = line.substring(6);
        if (data === '[DONE]') continue;
        try {
          const parsed = JSON.parse(data);
          const content = parsed.choices[0]?.delta?.content || '';
          accumulatedText += content;
          // 更新UI
          updateAiMessage(accumulatedText);
        } catch (error) {
          console.error('解析响应数据失败:', error);
        }
      }
    }
  }
  // 移除加载指示器
  // this.removeLoadingIndicator(aiMessageId);
}
const updateAiMessage = (content) => {
  const messageIndex = this.messages.findIndex(msg => msg.id === messageId);
  if (messageIndex !== -1) {
    this.messages[messageIndex].content = content;
    this.scrollToBottom();
  }
}
// Simple chat example
export async function quickChat() {
  const v = await client.chat.createAndPoll({
    bot_id: '7507240576233439286',
    additional_messages: [{
      role: RoleType.User,
      content: 'Hello!',
      content_type: 'text',
    }],
  });
  if (v.chat.status === ChatStatus.COMPLETED) {
    for (const item of v.messages) {
      console.log('[%s]:[%s]:%s', item.role, item.type, item.content);
    }
    console.log('usage', v.chat.usage);
  }
}